import { ElInput} from "element-plus"
import { defineComponent, ref } from "vue"
import { User, Lock } from '@element-plus/icons-vue'
import useInitRouter from "@/hooks/useInitRouter"
import './index.scss'
import { adminConfig } from "@Tea/model"
import { isFailCode, setLocalStorage, useGloablLoading } from "@Tea/utils"
import router from "@/router/permission"
import apiStore from "@/stores/apiStore"
import { ElMessage } from "element-plus"
import UserStore from "@/stores/UserStore"
import useInitUserInfo from "@/hooks/useInitUserInfo"

const useUserLogin = function () {
  const account = ref("")// 账号
  const password = ref("") // 密码
  const { loginAccount, getCustomMenu } = apiStore().api
  const { showLoading, closeLoading } = useGloablLoading()

  // 获取菜单
  const getMenu = async () => {
    try {
      const { data, code } = await getCustomMenu()
      closeLoading()
      if (isFailCode(code))  return
      if (data.children === undefined) {
        return ElMessage({
          type: "error",
          message:"当前账号没有可访问的菜单，请联系管理员添加！"
        })
      }
      setLocalStorage(`${adminConfig.systemCode}-routeTree`, data)
      useInitRouter(router, data)
      
      router.replace({ path: '/' })
      ElMessage({
        message: '登录成功',
        type: 'success',
      })
      
    } catch (e) {
      closeLoading()
    }
  }

  const login = async () => {
    try {
      showLoading({
        lock: true,
        text: '登录中',
      })
      const loginParam = { account: account.value, password: password.value }
      const { code, msg, data } = await loginAccount(loginParam)
      
      // 失败的请求会在响应拦截器中拦截
      if (isFailCode(code)) {
        console.log("请求失败了");
        closeLoading()
        return
      }

      // 将个人信息储存在本地储存中
      setLocalStorage(`${adminConfig.systemCode}-user`, data)
      useInitUserInfo(data)
      
      // 登录成功后，获取菜单
      // 这是是函数尾调用，小小的性能优化
      getMenu()
    } catch (e) {
      // 这里的错误一般也不用处理，也会在响应拦截中处理
      // 如果想测试服务端错误，可以在login的接口sql说随便改点东西让sql发生错误
      closeLoading()
      console.log("发生错误了");
    }
  }

  return { account, password, login }
}

export default defineComponent({
  setup() {

    const { account, password, login } = useUserLogin()

    return () =>(
      <div class="m-window m-fullBox loginBox allCenter">
        <div class="loginContent allCenter">
          <div class="m-leftForm m-window">
            <div class="m-logo">
              <span>{adminConfig.systemName}</span>
            </div>
            <div class="m-input demo-input-size">
              <ElInput
                class="m-top"
                v-model={account.value}
                clearable
                placeholder="请输入账号"
                prefixIcon={User}
              >
              </ElInput>
              <ElInput
                class="m-top"
                v-model={password.value}
                clearable
                type="password"
                placeholder="请输入密码"
                prefixIcon={Lock}
              ></ElInput>
              <div class="m-text-wrap ">
                <div
                  class="m-text cursorPointer"
                >
                  忘记密码？去找回
                </div>
              </div>
              <div class="m-loginBut allCenter cursorPointer" onClick={() => login()}>登录</div>
            </div>
            <p class="m-tips">为保障使用流畅，推荐谷歌(Google)</p>
          </div>
          <div class="m-rightImg">
            <img src="/src/assets/login_img.png" alt="" />
            <div class="m-version">
              <span>版本：{adminConfig.version}</span>
            </div>
          </div>
        </div>
      </div >
    )
  }
})